package com.suanfa.collect;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 集合所有子集
 */
public class SubSets {

    public static void main(String[] args) {
       /* SubSets subSets = new SubSets();
        int[] ch = {1};
        System.out.println(JSON.toJSONString(subSets.subsets(ch)));*/
        int[] ch = {1,2,3};
        System.out.println(JSON.toJSONString(binaryBit(ch)));

    }


    /**
     * 二进制01解决
     * @param nums
     * @return
     */
    public static List<List<Integer>> binaryBit(int[] nums) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        int count = 1 << nums.length;
        for(int i=0; i< count; i++){
            List<Integer> list = new ArrayList<>();
            for(int j = 0; j< nums.length; j++){
                if(((i>>j) &1 ) == 1){
                    list.add(nums[j]);
                }
            }
            res.add(list);
        }
        return res;
    }





    public List<List<Integer>> subsets(int[] nums) {

        int length = nums.length;
        int count = 2<<(length-1);//子集总数
        List<List<Integer>> result = new ArrayList<>();
        for(int i=0; i< count; i++){
            char[] ch = parseBin(i, length);
            List<Integer> list = new ArrayList<>();
            for(int j=0; j< ch.length; j++){
                if(ch[j]=='1'){
                    list.add(nums[j]);
                }
            }
            result.add(list);
        }
        return result;
    }

    public char[] parseBin(int num, int length){

        String s = Integer.toBinaryString(num);
        if(s.length() < length){
            StringBuilder r = new StringBuilder();
            for(int i =0; i< length-s.length();i++){
                r.append("0");
            }
            r.append(s);
            return r.toString().toCharArray();
        }

        return s.toCharArray();
    }

}
